package com.clouddms.controller;

import com.clouddms.dto.LoginRequest;
import com.clouddms.dto.LoginResponse;
import com.clouddms.dto.RegisterRequest;
import com.clouddms.entity.User;
import com.clouddms.service.auth.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 认证API控制器
 * 提供RESTful风格的认证接口
 */
@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*", maxAge = 3600)
public class AuthApiController {

    private static final Logger logger = LoggerFactory.getLogger(AuthApiController.class);

    @Autowired
    private UserService userService;

    /**
     * 用户登录API
     * @param loginRequest 登录请求
     * @param bindingResult 验证结果
     * @return 登录响应
     */
    @PostMapping("/login")
    public ResponseEntity<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest, 
                                               BindingResult bindingResult) {
        
        // 参数验证
        if (bindingResult.hasErrors()) {
            String errorMessage = bindingResult.getFieldErrors().get(0).getDefaultMessage();
            return ResponseEntity.badRequest().body(LoginResponse.failure(errorMessage));
        }

        try {
            LoginResponse response = userService.login(loginRequest);
            
            if (response.isSuccess()) {
                logger.info("用户登录成功: {}", loginRequest.getUsername());
                return ResponseEntity.ok(response);
            } else {
                logger.warn("用户登录失败: {}, 原因: {}", loginRequest.getUsername(), response.getMessage());
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
        } catch (Exception e) {
            logger.error("登录处理异常: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(LoginResponse.failure("系统内部错误，请稍后重试"));
        }
    }

    /**
     * 用户注册API
     * @param registerRequest 注册请求
     * @param bindingResult 验证结果
     * @return 注册响应
     */
    @PostMapping("/register")
    public ResponseEntity<LoginResponse> register(@Valid @RequestBody RegisterRequest registerRequest, 
                                                  BindingResult bindingResult) {
        
        // 参数验证
        if (bindingResult.hasErrors()) {
            String errorMessage = bindingResult.getFieldErrors().get(0).getDefaultMessage();
            return ResponseEntity.badRequest().body(LoginResponse.failure(errorMessage));
        }

        try {
            LoginResponse response = userService.register(registerRequest);
            
            if (response.isSuccess()) {
                logger.info("用户注册成功: {}", registerRequest.getUsername());
                return ResponseEntity.status(HttpStatus.CREATED).body(response);
            } else {
                logger.warn("用户注册失败: {}, 原因: {}", registerRequest.getUsername(), response.getMessage());
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            logger.error("注册处理异常: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(LoginResponse.failure("系统内部错误，请稍后重试"));
        }
    }

    /**
     * 检查用户认证状态
     * @param request HTTP请求
     * @return 认证状态信息
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> checkAuthStatus(HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 从请求属性中获取用户信息（由JWT过滤器设置）
            Long userId = (Long) request.getAttribute("userId");
            String username = (String) request.getAttribute("username");
            @SuppressWarnings("unchecked")
            java.util.Set<String> roles = (java.util.Set<String>) request.getAttribute("roles");
            
            if (userId != null && username != null) {
                response.put("authenticated", true);
                response.put("userId", userId);
                response.put("username", username);
                response.put("roles", roles);
                return ResponseEntity.ok(response);
            } else {
                response.put("authenticated", false);
                return ResponseEntity.ok(response);
            }
            
        } catch (Exception e) {
            logger.error("检查认证状态异常: {}", e.getMessage(), e);
            response.put("authenticated", false);
            response.put("error", "状态检查失败");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 用户注销API
     * @param request HTTP请求
     * @return 注销结果
     */
    @PostMapping("/logout")
    public ResponseEntity<Map<String, Object>> logout(HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = (String) request.getAttribute("username");
            
            // 从请求头获取Token并撤销
            String authHeader = request.getHeader("Authorization");
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                String token = authHeader.substring(7);
                userService.revokeToken(token);
            }
            
            response.put("success", true);
            response.put("message", "注销成功");
            
            if (username != null) {
                logger.info("用户注销: {}", username);
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("注销处理异常: {}", e.getMessage(), e);
            response.put("success", false);
            response.put("message", "注销失败");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 获取当前用户信息
     * @param request HTTP请求
     * @return 用户信息
     */
    @GetMapping("/me")
    public ResponseEntity<Map<String, Object>> getCurrentUser(HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Long userId = (Long) request.getAttribute("userId");
            String username = (String) request.getAttribute("username");
            @SuppressWarnings("unchecked")
            java.util.Set<String> roles = (java.util.Set<String>) request.getAttribute("roles");
            
            if (userId == null) {
                response.put("error", "未认证");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            // 获取用户详细信息
            Optional<User> userOpt = userService.findById(userId);
            if (userOpt.isPresent()) {
                User user = userOpt.get();
                response.put("userId", user.getUserId());
                response.put("username", user.getUsername());
                response.put("email", user.getEmail());
                response.put("roles", roles);
                response.put("isActive", user.getIsActive());
                response.put("createdAt", user.getCreatedAt());
                
                return ResponseEntity.ok(response);
            } else {
                response.put("error", "用户不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
            
        } catch (Exception e) {
            logger.error("获取用户信息异常: {}", e.getMessage(), e);
            response.put("error", "获取用户信息失败");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 检查用户名是否可用
     * @param username 用户名
     * @return 可用性结果
     */
    @GetMapping("/check-username")
    public ResponseEntity<Map<String, Object>> checkUsername(@RequestParam String username) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean exists = userService.findByUsername(username).isPresent();
            response.put("available", !exists);
            response.put("message", exists ? "用户名已存在" : "用户名可用");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("检查用户名可用性异常: {}", e.getMessage(), e);
            response.put("available", false);
            response.put("message", "检查失败");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
}